/**
 * 上传composer的依赖文件并更新
 */

var fs = require("fs"),
    path = require("path"),
    tool = require("./tool"),
    deployInfo = require("../../deploy-conf.json"),
    composerPath = !deployInfo.composer ? null : deployInfo.composer,
    composerFrom = composerPath ? composerPath.from : "",
    composerTo = composerPath ? composerPath.to : "",
    dirPath = path.resolve(__dirname, "../../" + composerFrom) + "/vendor",
    autoloadPath = path.resolve(__dirname, "../../" + composerFrom) + "/composer.json",
    installedPath = dirPath + "/composer/installed.json",
    type = 0; //0开发机环境，1预览机及上线环境

module.exports = function (urls, success, error, isOnline) {
    require("colors");
    require("shelljs/global");

    if(isOnline){
        type = 1;
        if (exec("cd " + composerFrom + "&& COMPOSER_HOME=\"/tmp\" php composer.phar update -vvv").code != 0) {
            console.log("\ncomposer update faild!".red);
            return;
        }

        update(urls, success, error);
    }else if (fs.existsSync(autoloadPath) && fs.existsSync(installedPath)) {
        var autoloadCtn = require(autoloadPath),
            installedCtn = require(installedPath);

        if (
            (autoloadCtn && autoloadCtn["require"]) &&
            (installedCtn && installedCtn.length)
        ) {
            update(urls, success, error);
        }else{
            success && success();
        }
    } else {
        success && success();
    }
};

function update(urls, success, error) {
    var request = require("request"),
        async = require("async"),
        files = [];

    console.log("\nupload composer dependences...".green);

    tool.getAllFilePath(dirPath, files);

    async.eachSeries(urls, function (url, cbSeries) {
        var receiver = url.receiver,
            dist = url.dist + composerTo;

        async.eachLimit(files, 10, function (file, cbLimit) {
            request.post({
                url: receiver,
                formData: {
                    to: dist + "/" + file.dist,
                    file: fs.createReadStream(file.path)
                }
            }, function (err, httpResponse, body) {
                var statusCode = httpResponse && httpResponse.toJSON().statusCode;

                if (err || statusCode != 200 || body != 0) {
                    cbLimit("\nupload error!".red);
                } else {
                    console.log(file.path);
                    cbLimit();
                }
            });

        }, function (err) {
            if (err) {
                cbSeries('\nupload error!'.red);
            } else {
                cbSeries();
            }
        });

    }, function (err) {
        if (err) {
            console.log("composer files upload faild!".red);
        } else {
            console.log("\nupload composer.json to merge...".green);

            async.eachSeries(urls, function (url, callback) {
                var receiver = url.receiver,
                    dist = url.dist + composerTo;

                receiver = receiver.slice(0, receiver.lastIndexOf("/") + 1) + "composerMerge.php";

                request.post({
                    url: receiver,
                    formData: {
                        autoload: dist + "/" + "composer.json",
                        autoload_file: fs.readFileSync(autoloadPath),
                        installed: dist + "/" + "vendor/composer/installed.json",
                        installed_file: fs.readFileSync(installedPath),
                        command: "cd " + dist + " && COMPOSER_HOME=\"/tmp\" php composer.phar dump-autoload -o",
                        type: type
                    }
                }, function (err, httpResponse, body) {
                    var statusCode = httpResponse && httpResponse.toJSON().statusCode;

                    try {
                        body = body && JSON.parse(body);
                    } catch (e) {
                        body = {
                            no: -1,
                            msg: "server is something wrong!"
                        }
                    }

                    if (err || statusCode != 200 || body.no != 0) {
                        tool.log(JSON.stringify(body) + " ");
                        callback("upload error!".red);
                    } else {
                        callback();
                    }
                });
            }, function (err) {
                if (err) {
                    console.log("upload composer.json faild!".red);
                    error && error();
                } else {
                    success && success();
                }
            });
        }
    });
}
